# coding=utf-8
import time

import traceback
from monthdelta import monthdelta
import datetime
import requests
from pymongo import MongoClient
import Utils
import sys
from pandas import DataFrame
import pandas as pd
from pymongo import MongoClient
from simplemysql import SimpleMysql

reload(sys)
sys.setdefaultencoding('utf-8')

mysqlDB = SimpleMysql(
    host="121.40.54.235",
    db="stock-grab",
    user="root",
    passwd="Dream2015",
    charset="utf8",
    keep_alive=True  # try and reconnect timedout mysql connections?
)

def save_to_mysql(file):

    max_day_cursor = mysqlDB.query("select count(*) from newlove_book where name = %s",[file['name']])
    count = max_day_cursor.fetchone()[0]
    if count == 0:
        record = {}
        record['name'] = file['name']
        record['type'] = 'address'
        record['description'] = '云盘提取密码:' + file['password']
        record['download_address'] = file['share_address']
        record['fileSize'] = 0
        record['deleted'] = 0
        record['downloadedCount'] = 0
        record['createTime'] = datetime.datetime.now()
        record['modifyTime'] = datetime.datetime.now()
        mysqlDB.insert("newlove_book", record)
        #Utils.logger.info(file['name'] + " is saved to mysql")
        mysqlDB.commit()
    else:
        Utils.logger.info(file['name'] + " already exist in mysql")


with open('baidu_book.txt', 'r') as file:
    lines = file.readlines()
    for line in lines:
        parts = line.split("\t")
        file = {}
        file['name'] = parts[0].strip()
        file['share_address'] = parts[1].strip()
        file['password'] = parts[2].strip()
        save_to_mysql(file)








